import logging
from datetime import datetime
from typing import Optional

logger = logging.getLogger(__name__)


def parse_date(date_str: Optional[str]) -> Optional[datetime]:
    """将日期字符串解析为datetime对象"""
    date_str = date_str.strip() if date_str else None
    if not date_str:
        return None
    # 定义可能的日期格式["2025-01-01", "2025.01.01", "2025/01/01", "20250101", "2025-01-01 00:00:00"]
    date_formats = ["%Y-%m-%d", "%Y.%m.%d", "%Y/%m/%d", "%Y%m%d", "%Y-%m-%d %H:%M:%S"]

    # 尝试每种日期格式
    for date_format in date_formats:
        try:
            return datetime.strptime(date_str, date_format)
        except ValueError:
            continue

    # 如果所有格式都失败，记录错误并返回None
    logger.warning(f"无法解析日期字符串: {date_str}")
    return None
